package com.cndongtai.controller.torchn;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cndongtai.controller.BaseController;
import com.cndongtai.net.redis.RedisServer;
import com.cndongtai.po.TorchnAppUserInfo;
import com.cndongtai.po.TorchnBatteryCollectRecord;
import com.cndongtai.po.TorchnInverterCollectRecord;
import com.cndongtai.po.TorchnUserInfo;
import com.cndongtai.po.UploadFile;
import com.cndongtai.service.torchn.TorchnAppLoginService;
import com.cndongtai.service.torchn.TorchnLoginService;
import com.cndongtai.service.torchn.TorchnService;
import com.cndongtai.service.upload.UploadService;
import com.cndongtai.service.weixin.WeixinService;
import com.cndongtai.util.BASE64Util;
import com.cndongtai.util.DateUtil;
import com.cndongtai.util.MD5;
import com.cndongtai.util.MailUtil;
import com.cndongtai.util.ValidateCodeUtil;
import com.cndongtai.util.ValidateUtil;

@Controller
@RequestMapping("/torchnapp")
public class TorchnAppLoginController extends BaseController {
	
	@Resource(name = "torchnAppLoginService")
	private TorchnAppLoginService torchnAppLoginService;
	
	@Resource(name="torchnLoginService")
	private TorchnLoginService torchnLoginService;
	
	@Resource(name = "torchnService")
	private TorchnService torchnService;
	
	@Resource(name = "weixinService")
	private WeixinService weixinService;
	
	@Resource(name = "uploadService")
	private UploadService uploadService;
	
	private static final long FILE_MAX_SIZE = 1024 * 1024 * 10;
	
	private RedisServer redis = RedisServer.getInstance();
	
	public final Logger log = Logger.getLogger(this.getClass());
	
	@RequestMapping("register")
	@ResponseBody
	public void register(String mobile, String email, String password) {
		
		JSONObject result = new JSONObject();
		
		// 获取注册信息
		/*String mobile = this.getValue("mobile");
		String mobile1 = this.getPostValue("mobile");
		String email = this.getValue("email");
		String password = this.getValue("password");*/
		
		// 校验注册信息
		
		if(ValidateUtil.empty(mobile)) {
			result.put("code", "0001");
			result.put("msg", "手机号不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(password)) {
			result.put("code", "0001");
			result.put("msg", "密码不能为空");
			this.writeData(result);
			return;
		}
		
		
		if(!ValidateUtil.checkMobile(mobile)) {
			result.put("code", "0001");
			result.put("msg", "手机号不正确，请重新填写");
			this.writeData(result);
			return;
		}
		
		if(!ValidateUtil.checkEmail(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不正确，请重新填写");
			this.writeData(result);
			return;
		}
		
		// 构建用户信息
		TorchnAppUserInfo userInfo = new TorchnAppUserInfo();
		userInfo.setMobile(mobile);
		userInfo.setEmail(email);
		userInfo.setUsername("torchn"+mobile);
		userInfo.setCreateTime(new Date());
		userInfo.setActiveFlag(1);
		
		List<TorchnAppUserInfo> userList = torchnAppLoginService.queryTorchnAppUserInfoList(userInfo);
		if(userList!=null && userList.size()>0) {
			result.put("code", "0001");
			result.put("msg", "该手机号或邮箱已被注册");
			this.writeData(result);
			return;
		}
		
		String pwdStr = new MD5().getMD5ofStr(password);
		userInfo.setPassword(pwdStr);
		
		int res = torchnAppLoginService.addTorchnAppUserInfo(userInfo);
		if(res>0) {
			result.put("code", "0000");
			result.put("msg", "注册成功");
//			result.put("msg", "注册成功,请到注册邮箱激活用户");
			
			// 发送注册邮件
			/*try {
				String sign = BASE64Util.encryptBASE64(userInfo.getUsername().getBytes());
				MailUtil.sendMail(email,"TorchnApp用户注册激活", "欢迎注册成为Torchn用户，您的账号还未激活，请点击链接完成用户激活，https://www.365ctrl.com/torchnapp/active.do?sign="+sign);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			
		}else {
			result.put("code", "0001");
			result.put("msg", "注册失败");
		}
		
		this.writeData(result);
	}
	
	
	@RequestMapping("login")
	@ResponseBody
	public void login(String username, String password) {
		
		JSONObject result = new JSONObject();
		
		// 获取登陆信息
		/*String username = this.getValue("username");
		String password = this.getValue("password");*/
		
		
		// 校验注册信息
		
		if(ValidateUtil.empty(username)) {
			result.put("code", "0001");
			result.put("msg", "用户名不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(password)) {
			result.put("code", "0001");
			result.put("msg", "密码不能为空");
			this.writeData(result);
			return;
		}
		
		// 根据用户名查询用户信息
		TorchnAppUserInfo userInfo = new TorchnAppUserInfo();
		userInfo.setMobile(username);
		userInfo.setEmail(username);
		userInfo.setUsername(username);
		
		
		List<TorchnAppUserInfo> userList = torchnAppLoginService.queryTorchnAppUserInfoList(userInfo);
		if(userList==null || userList.size()<1) {
			result.put("code", "0001");
			result.put("msg", "用户名或密码错误，请重试");
			this.writeData(result);
			return;
		}
		
		userInfo = userList.get(0);
		
		String pwdStr = new MD5().getMD5ofStr(password);
		
		// 校验密码
		if(pwdStr.equals(userInfo.getPassword())) {
			
			if(userInfo.getActiveFlag().equals(0)) {
				result.put("code", "0001");
				result.put("msg", "该用户未激活，请到注册邮箱激活该用户");
				this.writeData(result);
				return;
			}
			
			result.put("code", "0000");
			result.put("msg", "登陆成功");
			
			String token = UUID.randomUUID().toString();
			// 登陆成功，创建token身份令牌
			redis.set(token, userInfo.getUserId()+"", 60*60*24*30);
			result.put("token", token);
		}else {
			result.put("code", "0001");
			result.put("msg", "用户名或密码错误，请重试");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("weixinlogin")
	@ResponseBody
	public void weixinlogin(String weixin_access_code) {
		
		JSONObject result = new JSONObject();
		
		// 获取微信临时授权码
		String code = weixin_access_code;//this.getValue("weixin_access_code");
		
		log.error("weixinlogin code==>"+code);
		
		if(ValidateUtil.empty(code)) {
			result.put("code", "0001");
			result.put("msg", "登录失败");
			this.writeData(result);
			return;
		}
		
		// 调用微信接口获取access_token
		JSONObject accessTokenResult = weixinService.getAccessToken(code);
		if(accessTokenResult == null) {
			result.put("code", "0002");
			result.put("msg", "微信获取accessTokenapi请求失败");
			this.writeData(result);
			return;
		}
		
		String accessToken = accessTokenResult.get("access_token")==null?null:accessTokenResult.getString("access_token");
		if(ValidateUtil.empty(accessToken)) {
			result.put("code", "0003");
			result.put("msg", "accessToken获取失败");
			this.writeData(result);
			return;
		}
		
		// 判断用户是否存在
		String openid = accessTokenResult.getString("openid");
		String unionid = accessTokenResult.getString("unionid");
		if(ValidateUtil.empty(openid)) {
			result.put("code", "0004");
			result.put("msg", "openid获取失败");
			this.writeData(result);
			return;
		}
		
		TorchnUserInfo userInfo = torchnLoginService.queryTorchnUserInfo(openid);
		if(userInfo != null) {
			result.put("code", "0000");
			result.put("msg", "登陆成功");
			
			String token = UUID.randomUUID().toString();
			// 登陆成功，创建token身份令牌
			redis.set(token, "openid:"+openid, 60*60*24*30);
			result.put("token", token);
			this.writeData(result);
			return;
		}
		
		
		// 根据微信接口获取用户信息
		JSONObject userInfoJson = weixinService.getUserInfo(accessToken, openid);
		TorchnUserInfo user = new TorchnUserInfo();
		user.setNickName(userInfoJson.getString("nickname"));
		user.setGender(userInfoJson.getInt("sex"));
		user.setCity(userInfoJson.getString("city"));
		user.setProvince(userInfoJson.getString("province"));
		user.setCountry(userInfoJson.getString("country"));
//		user.setLanguage(userInfoJson.getString("language"));
		user.setAvatarUrl(userInfoJson.getString("headimgurl"));
		user.setOpenid(openid);
		user.setUnionid(unionid);
		user.setCreateTime(new Date());
		
		if(!torchnLoginService.addTorchnUserInfo(user)) {
			result.put("code", "0001");
			result.put("msg", "微信授权失败");
			this.writeData(result);
			return;
		}
		
		result.put("code", "0000");
		result.put("msg", "登陆成功");
		
		String token = UUID.randomUUID().toString();
		// 登陆成功，创建token身份令牌
		redis.set(token, "openid:"+openid, 60*60*24*30);
		result.put("token", token);
		result.put("", user.getAvatarUrl());
		this.writeData(result);
		return;
	}
	
	@RequestMapping("logout")
	@ResponseBody
	public void logout(String token) {
		
		JSONObject result = new JSONObject();
		
		// 获取登陆信息
//		String token = this.getValue("token");
		
		// 校验注册信息
		String userId = redis.get("token");
		
		if(ValidateUtil.empty(userId)) {
			result.put("code", "0001");
			result.put("msg", "退出失败");
			this.writeData(result);
			return;
		}
		
		redis.del(token);
		
		result.put("code", "0000");
		result.put("msg", "退出成功");
			
		this.writeData(result);
	}
	
	@RequestMapping("active")
	@ResponseBody
	public void active(String sign) {
		
		JSONObject result = new JSONObject();
		
		// 获取登陆信息
//		String sign = this.getValue("sign");
		
		// 校验注册信息
		if(sign==null || "".equals(sign)) {
			result.put("code", "0001");
			result.put("msg", "激活失败");
			this.writeData(result);
			return;
		}
		
		String userName;
		try {
			userName = new String(BASE64Util.decryptBASE64(sign));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "激活失败");
			this.writeData(result);
			return;
		}
		
		int res = torchnAppLoginService.activedTorchnAppUser(userName);
		if(res>0) {
			result.put("code", "0000");
			result.put("msg", "激活成功");
		}else {
			result.put("code", "0001");
			result.put("msg", "激活失败");
		}
			
		this.writeData(result);
	}
	
	
	@RequestMapping("modifypwd")
	@ResponseBody
	public void modifypwd(String token, String password) {
		
		JSONObject result = new JSONObject();
		
		// 获取登陆信息
//		String token = this.getValue("token");
		
		String userIdStr = redis.get(token);
		// 校验注册信息
		if(userIdStr==null || "".equals(userIdStr)) {
			result.put("code", "0001");
			result.put("msg", "登陆已失效，请重新登陆");
			this.writeData(result);
			return;
		}else if(userIdStr.startsWith("openid:")) {
			result.put("code", "0001");
			result.put("msg", "微信登陆用户不支持修改密码");
			this.writeData(result);
			return;
		}
		
		// 获取密码信息
//		String password = this.getValue("password");
		if(ValidateUtil.empty(password)) {
			result.put("code", "0001");
			result.put("msg", "密码不能为空");
			this.writeData(result);
			return;
		}
		
		// 修改密码
		String pwdStr = new MD5().getMD5ofStr(password);
		
		// 调用修改密码接口
		int res = torchnAppLoginService.modifyTorchnAppUserPassword(userIdStr, pwdStr);
		if(res>0) {
			result.put("code", "0000");
			result.put("msg", "密码修改成功");
		}else {
			result.put("code", "0001");
			result.put("msg", "密码修改失败");
		}
			
		this.writeData(result);
	}
	
	@RequestMapping("getValidateCode")
	@ResponseBody
	public void getValidateCode(String email) {
		
		JSONObject result = new JSONObject();
		
		// 获取登陆信息
//		String email = this.getValue("email");
		if(ValidateUtil.empty(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不能为空");
			this.writeData(result);
			return;
		}

		if(!ValidateUtil.checkEmail(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不正确，请重新填写");
			this.writeData(result);
			return;
		}
		
		
		// 生成邮箱验证码
		String validateCode = ValidateCodeUtil.generateValidateCode(6);
		
		// 放入缓存
		redis.set("validatecode_"+email, validateCode, 120);
		
		// 发送邮箱验证码
		try {
			MailUtil.sendMail(email,"TorchnApp用户邮箱验证码", "您的邮箱验证码为："+validateCode);
			result.put("code", "0000");
			result.put("msg", "验证码发送成功");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "验证码发送失败");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "验证码发送失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("forgetPwdReset")
	@ResponseBody
	public void forgetPwdReset(String email, String validateCode, String password) {
		
		JSONObject result = new JSONObject();
		
		// 获取
		/*String email = this.getValue("email");
		String validateCode = this.getValue("validateCode");
		String password = this.getValue("password");*/
		
		if(ValidateUtil.empty(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不能为空");
			this.writeData(result);
			return;
		}

		if(!ValidateUtil.checkEmail(email)) {
			result.put("code", "0001");
			result.put("msg", "邮箱不正确，请重新填写");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(validateCode)) {
			result.put("code", "0001");
			result.put("msg", "验证码不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(password)) {
			result.put("code", "0001");
			result.put("msg", "密码不能为空");
			this.writeData(result);
			return;
		}
		
		// 校验邮箱验证码
		String cacheCode = redis.get("validatecode_"+email);
		// 清除验证码
		redis.del("validatecode_"+email);
		
		if(!validateCode.equals(cacheCode)) {
			result.put("code", "0001");
			result.put("msg", "验证码输入错误");
			this.writeData(result);
			return;
		}
		
		TorchnAppUserInfo userInfo = torchnAppLoginService.queryTorchnAppUserInfoByEmail(email);
		if(userInfo==null) {
			result.put("code", "0001");
			result.put("msg", "该邮箱未注册TorchnApp用户");
			this.writeData(result);
			return;
		}
		
		// 修改密码
		String pwdStr = new MD5().getMD5ofStr(password);
		
		// 调用修改密码接口
		int res = torchnAppLoginService.modifyTorchnAppUserPassword(userInfo.getUserId()+"", pwdStr);
		if(res>0) {
			result.put("code", "0000");
			result.put("msg", "密码修改成功");
		}else {
			result.put("code", "0001");
			result.put("msg", "密码修改失败");
		}
			
		this.writeData(result);
	}
	
	@RequestMapping("/saveQuantity")
	@ResponseBody
	public void saveQuantity(String deviceName, String batterygroupvol, String batterygroupcurrent, String timeinterval, 
			String voltagecore1, String voltagecore2, String voltagecore3, String voltagecore4) {
		JSONObject result = new JSONObject();
		
		/*String deviceName = this.getValue("deviceName");
		String batterygroupvol = this.getValue("batterygroupvol");
		String batterygroupcurrent = this.getValue("batterygroupcurrent");
		String timeinterval = this.getValue("timeinterval");*/
		
		try {
			
			log.error("deviceName==>"+deviceName);
			log.error("batterygroupvol==>"+batterygroupvol);
			log.error("batterygroupcurrent==>"+batterygroupcurrent);
			log.error("timeinterval==>"+timeinterval);
			log.error("voltagecore1==>"+voltagecore1);
			log.error("voltagecore2==>"+voltagecore2);
			log.error("voltagecore3==>"+voltagecore3);
			log.error("voltagecore4==>"+voltagecore4);
			
			TorchnBatteryCollectRecord record = new TorchnBatteryCollectRecord();
			
			record.setDeviceName(deviceName);
			record.setBatteryVol(Double.valueOf(batterygroupvol));
			record.setBatteryCurrent(Double.valueOf(batterygroupcurrent));
			record.setVoltagecore1(ValidateUtil.empty(voltagecore1)?0:Double.valueOf(voltagecore1));
			record.setVoltagecore2(ValidateUtil.empty(voltagecore2)?0:Double.valueOf(voltagecore2));
			record.setVoltagecore3(ValidateUtil.empty(voltagecore3)?0:Double.valueOf(voltagecore3));
			record.setVoltagecore4(ValidateUtil.empty(voltagecore4)?0:Double.valueOf(voltagecore4));
			
			record.setTimeInterval(Integer.valueOf(timeinterval));
			record.setCollectTime(new Date());
			
			if(torchnService.addTorchnBatteryCollectRecord(record)) {
				result.put("code", "0000");
				result.put("msg", "success");	
			}else {
				result.put("code", "0001");
				result.put("msg", "fail");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据插入失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/saveQuantityHis")
	@ResponseBody
	public void saveQuantityHis(String deviceName, String batterygroupvol, String batterygroupcurrent, String timeinterval, 
			String voltagecore1, String voltagecore2, String voltagecore3, String voltagecore4, String collectTime) {
		JSONObject result = new JSONObject();
		
		/*String deviceName = this.getValue("deviceName");
		String batterygroupvol = this.getValue("batterygroupvol");
		String batterygroupcurrent = this.getValue("batterygroupcurrent");
		String timeinterval = this.getValue("timeinterval");*/
		
		try {
			log.error("deviceName==>"+deviceName);
			log.error("batterygroupvol==>"+batterygroupvol);
			log.error("batterygroupcurrent==>"+batterygroupcurrent);
			log.error("timeinterval==>"+timeinterval);
			log.error("voltagecore1==>"+voltagecore1);
			log.error("voltagecore2==>"+voltagecore2);
			log.error("voltagecore3==>"+voltagecore3);
			log.error("voltagecore4==>"+voltagecore4);
			
			TorchnBatteryCollectRecord record = new TorchnBatteryCollectRecord();
			
			record.setDeviceName(deviceName);
			record.setBatteryVol(Double.valueOf(batterygroupvol));
			record.setBatteryCurrent(Double.valueOf(batterygroupcurrent));
			record.setVoltagecore1(ValidateUtil.empty(voltagecore1)?0:Double.valueOf(voltagecore1));
			record.setVoltagecore2(ValidateUtil.empty(voltagecore2)?0:Double.valueOf(voltagecore2));
			record.setVoltagecore3(ValidateUtil.empty(voltagecore3)?0:Double.valueOf(voltagecore3));
			record.setVoltagecore4(ValidateUtil.empty(voltagecore4)?0:Double.valueOf(voltagecore4));
			
			record.setTimeInterval(Integer.valueOf(timeinterval));
			if(collectTime!=null && !"".equals(collectTime)) {
				record.setCollectTime(DateUtil.parseDateFull(collectTime));
			}else {
				result.put("code", "0001");
				result.put("msg", "采集时间格式错误");
				this.writeData(result);
				return;
			}
			
			
			if(torchnService.addTorchnBatteryCollectRecord(record)) {
				result.put("code", "0000");
				result.put("msg", "success");	
			}else {
				result.put("code", "0001");
				result.put("msg", "数据保存失败");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据异常");
			log.error("发生异常", e);
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/queryBatteryCollectRecord")
	@ResponseBody
	public void queryBatteryCollectRecord(String deviceName) {
		JSONObject result = new JSONObject();
		
		try {
			log.error("deviceName==>"+deviceName);
			// 校验deviceName
			if(ValidateUtil.empty(deviceName)) {
				result.put("code", "0001");
				result.put("msg", "设备名称不能为空");
				this.writeData(result);
				return;
			}
			
			List<TorchnBatteryCollectRecord> recordList = torchnService.queryBatteryCollectRecord(deviceName);
			if(recordList!=null && recordList.size()>0) {
				for(TorchnBatteryCollectRecord record : recordList) {
					record.setCollectTimeStr(DateUtil.timeFormat(record.getCollectTime()));
					record.setCollectTime(null);
				}
			}
					
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("dataList", recordList);
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据插入失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/queryChargeQuantity")
	@ResponseBody
	public void queryChargeQuantity(String deviceName) {
		JSONObject result = new JSONObject();
		
//		String deviceName = this.getValue("deviceName");
		
		try {
			double quantity = torchnService.queryBatteryChargeQuantity(deviceName);
			
			DecimalFormat format = new DecimalFormat("#.######");
			
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("quantity", format.format(Math.abs(quantity)/3600/1000));
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "success");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/queryWorkQuantity")
	@ResponseBody
	public void queryWorkQuantity(String deviceName) {
		JSONObject result = new JSONObject();
		
//		String deviceName = this.getValue("deviceName");
		
		try {
			double quantity = torchnService.queryBatteryWorkQuantity(deviceName);
			DecimalFormat format = new DecimalFormat("#.######");
			
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("quantity", format.format(Math.abs(quantity)/3600/1000));
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "success");
		}
		
		this.writeData(result);
	}
	
	/**
	 * 查询用户信息
	 * @param deviceName
	 */
	@RequestMapping("/queryUserInfo")
	@ResponseBody
	public void queryUserInfo(String token) {
		JSONObject result = new JSONObject();
		
		String userIdStr = redis.get(token);
		// 校验注册信息
		if(userIdStr==null || "".equals(userIdStr)) {
			result.put("code", "0001");
			result.put("msg", "登陆已失效，请重新登陆");
			this.writeData(result);
			return;
		}else if(userIdStr.startsWith("openid:")) {
			TorchnUserInfo userInfo = torchnLoginService.queryTorchnUserInfo(userIdStr.substring(7));
			
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("nickname", userInfo.getNickName()==null ? "" : userInfo.getNickName());
			
			// 获取头像地址
			result.put("headerImage", userInfo.getAvatarUrl());
			
			result.put("code", "0001");
			result.put("msg", "微信登陆用户不支持修改密码");
			this.writeData(result);
			return;
		}
		
		try {
			Long userId = Long.parseLong(userIdStr);
			
			TorchnAppUserInfo userInfo = torchnAppLoginService.queryTorchnAppUserInfoById(userId);
			
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("nickname", userInfo.getNickname()==null ? "" : userInfo.getNickname());
			
			// 获取头像地址
			UploadFile file = uploadService.queryUploadFileById(userInfo.getHeaderPicId());
			result.put("headerImage", file==null ? "" : "http://wwww.365ctrl.com/pic/"+file.getFilePath());
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "查询失败");
		}
		
		this.writeData(result);
	}
	
	/**
	 * 修改用户昵称
	 * @param deviceName
	 */
	@RequestMapping("/modifyNickname")
	@ResponseBody
	public void modifyNickname(String token, String nickname) {
		JSONObject result = new JSONObject();
		
		String userIdStr = redis.get(token);
		// 校验注册信息
		if(userIdStr==null || "".equals(userIdStr)) {
			result.put("code", "0001");
			result.put("msg", "登陆已失效，请重新登陆");
			this.writeData(result);
			return;
		}else if(userIdStr.startsWith("openid:")) {
			result.put("code", "0001");
			result.put("msg", "微信登陆用户不支持信息修改");
			this.writeData(result);
			return;
		}
		
		try {
			Long userId = Long.parseLong(userIdStr);
			
			TorchnAppUserInfo userInfo = torchnAppLoginService.queryTorchnAppUserInfoById(userId);
			if(userInfo == null) {
				result.put("code", "0001");
				result.put("msg", "用户异常，操作失败");
				this.writeData(result);
				return;
			}
			
			userInfo.setNickname(nickname);
			int res = torchnAppLoginService.modifyNickname(userInfo);
			if(res>0) {
				result.put("code", "0000");
				result.put("msg", "success");
			}else {
				result.put("code", "0001");
				result.put("msg", "网络异常，操作失败");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据异常，操作失败");
		}
		
		this.writeData(result);
	}
	
	/**
	 * 修改头像
	 * @param deviceName
	 */
	@RequestMapping("/modifyHeaderImage")
	@ResponseBody
	public void modifyHeaderImage(String token, Long headerImageId) {
		JSONObject result = new JSONObject();
		
		String userIdStr = redis.get(token);
		// 校验注册信息
		if(userIdStr==null || "".equals(userIdStr)) {
			result.put("code", "0001");
			result.put("msg", "登陆已失效，请重新登陆");
			this.writeData(result);
			return;
		}else if(userIdStr.startsWith("openid:")) {
			result.put("code", "0001");
			result.put("msg", "微信登陆用户不支持信息修改");
			this.writeData(result);
			return;
		}
		
		try {
			Long userId = Long.parseLong(userIdStr);
			
			TorchnAppUserInfo userInfo = torchnAppLoginService.queryTorchnAppUserInfoById(userId);
			if(userInfo == null) {
				result.put("code", "0001");
				result.put("msg", "用户异常，操作失败");
				this.writeData(result);
				return;
			}
			
			userInfo.setHeaderPicId(headerImageId);
			int res = torchnAppLoginService.modifyHeaderImage(userInfo);
			if(res>0) {
				result.put("code", "0000");
				result.put("msg", "success");
			}else {
				result.put("code", "0001");
				result.put("msg", "网络异常，操作失败");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据异常，操作失败");
		}
		
		this.writeData(result);
	}
	
	@ResponseBody
	@RequestMapping("/uploadFile")
	public void uploadFile(String token, MultipartFile file) {
		JSONObject result = new JSONObject();
		
		String userIdStr = redis.get(token);
		// 校验注册信息
		if(userIdStr==null || "".equals(userIdStr)) {
			result.put("code", "0001");
			result.put("msg", "登陆已失效，请重新登陆");
			this.writeData(result);
			return;
		}else if(userIdStr.startsWith("openid:")) {
			result.put("code", "0001");
			result.put("msg", "微信登陆用户不支持图片上传");
			this.writeData(result);
			return;
		}
		
		if(null!=file && file.getSize()>0) {
			log.error("uploadFileName==>"+file.getOriginalFilename());
			// 校验扩展名
			if (null == file
					|| !ValidateUtil.checkImageFileExt(file.getOriginalFilename())) {
				
				result.put("success", "0001");
				result.put("msg", "文件格式错误！");
				this.writeData(result);
				return;
			}

			// 判断文件大小
			if (file.getSize() > FILE_MAX_SIZE) {
				result.put("success", "0001");
				result.put("msg", "文件大小不得超过10M！");
				this.writeData(result);
				return;
			}

			UploadFile uploadFile;
			try {
				uploadFile = uploadService.uploadFileFromApp(userIdStr, file);
				if(null==uploadFile) {
					result.put("success", "0001");
					result.put("msg", "文件上传失败！");
				}else {
//					SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					result.put("success", "0000");
					result.put("msg", "文件上传成功！");
					result.put("fileId", uploadFile.getId().toString());
//					result.put("filePath", uploadFile.getFilePath());
//					result.put("fileName", uploadFile.getFileName());
//					result.put("uploadTime", sf.format(uploadFile.getUploadTime()));
				}
			} catch (Exception e) {
				log.error(e.getMessage());;
				result.put("success", "0001");
				result.put("msg", "文件格式错误，上传失败！");
			}
		}else {
			result.put("success", "0001");
			result.put("msg", "文件上传失败！");
		}

		this.writeData(result);
	}
	
	/**
	 * APP用户协议
	 * @param deviceName
	 */
	@RequestMapping("/queryAgreement")
	@ResponseBody
	public void queryAgreement(Integer type) {
		JSONObject result = new JSONObject();
		
		try {
			if(type==null) {
				result.put("code", "0001");
				result.put("msg", "查询失败");
				this.writeData(result);
				return;
			}
			
			String agreement = torchnAppLoginService.queryAgreement(type);
			
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("agreement", agreement==null?"":agreement);
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "查询失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/saveInverterCollect")
	@ResponseBody
	public void saveInverterCollect(TorchnInverterCollectRecord record) {
		JSONObject result = new JSONObject();
		
		try {
			
			log.error("TorchnInverterCollectRecord==>"+record.toString());

			if(ValidateUtil.empty(record.getDeviceName())) {
				result.put("code", "0001");
				result.put("msg", "设备名称不能为空");
				this.writeData(result);
				return;
			}
			
			if(ValidateUtil.notEmpty(record.getCollectTimeStr())) {
				record.setCollectTime(DateUtil.parseDateFull(record.getCollectTimeStr()));
			}else {
				result.put("code", "0001");
				result.put("msg", "采集时间格式错误");
				this.writeData(result);
				return;
			}
			
//			record.setCollectTime(new Date());
			
			if(torchnService.addTorchnInverterCollectRecord(record)) {
				result.put("code", "0000");
				result.put("msg", "success");	
			}else {
				result.put("code", "0001");
				result.put("msg", "fail");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据插入失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/queryInverterCollectRecord")
	@ResponseBody
	public void queryInverterCollectRecord(String deviceName) {
		JSONObject result = new JSONObject();
		
		try {
			log.error("deviceName==>"+deviceName);
			// 校验deviceName
			if(ValidateUtil.empty(deviceName)) {
				result.put("code", "0001");
				result.put("msg", "设备名称不能为空");
				this.writeData(result);
				return;
			}
			
			List<TorchnInverterCollectRecord> recordList = torchnService.queryInverterCollectRecord(deviceName);
			if(recordList!=null && recordList.size()>0) {
				for(TorchnInverterCollectRecord record : recordList) {
					record.setCollectTimeStr(DateUtil.timeFormat(record.getCollectTime()));
					record.setCollectTime(null);
				}
			}
					
			result.put("code", "0000");
			result.put("msg", "success");
			result.put("dataList", recordList);
		}catch(Exception e) {
			e.printStackTrace();
			result.put("code", "0001");
			result.put("msg", "数据插入失败");
		}
		
		this.writeData(result);
	}
	

}
